package gcu.module.rbac.rest;

import gcu.common.context.SecurityContextHolder;
import gcu.common.domain.BasePageController;
import gcu.module.rbac.daomain.Role;
import gcu.module.rbac.daomain.User;
import gcu.module.rbac.service.RoleService;
import gcu.module.rbac.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * Created by haol on 2016/9/21.
 */
@RestController
@RequestMapping("/rest/user")
public class UserRestController {

      private Logger logger = LoggerFactory.getLogger(UserRestController.class);

      @Autowired
      private UserService userService;
      @Autowired
      private RoleService roleService;

      @RequestMapping(value = "/checkName", method = RequestMethod.POST)
      public boolean checkName(User user) {
            user = userService.queryUserByName(user.getUserName());
            if (user == null) {
                  return true;
            } else {
                  return false;
            }
      }

      @RequestMapping(value = "/saveUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
      public void saveUser(@RequestBody User user) {
            if (user.getId() == null) {
                  userService.add(user);
            } else {
                  userService.update(user);
            }
      }
      @RequestMapping(value = "/checkRole", method = RequestMethod.POST)
      public boolean checkRole() {
            User user = SecurityContextHolder.getUser();
            List<Role> roles = roleService.queryRoleByUser(user.getId());
            for(Role role :roles){
                  if (role.getRoleSn().equals("SUPER")){
                        return true;
                  }
            }
           return false;
      }
      @RequestMapping(value = "/uppwd",method = RequestMethod.POST)
      public boolean pwd(String username,String password) {
            try{
                  userService.updatePwd(username,password);
            }catch (Exception e){
                  return false;
            }
            return true;

      }
}
